//
//  OADueInViewController.m
//  OASystem
//
//  Created by zhoupengfei on 15/11/15.
//  Copyright © 2015年 zpf. All rights reserved.
//

#import "OADueInViewController.h"
#import "HttpTools.h"
#import "DueInListModel.h"
#import "FileListCell.h"
#import "UIAlertView+Blocks.h"
#import "MBProgressHUD.h"
#import "Toast+UIView.h"
#import "OADueInDetailController.h"
#import "OAToolBox.h"

@interface OADueInViewController ()
@property(nonatomic,assign)BOOL isSearching;
@property(nonatomic,copy)NSString * searchText;
@end

@implementation OADueInViewController

- (void)viewDidLoad {
    self.isNeedRefresh = YES;
    [super viewDidLoad];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    [self setRightItem];
    [self.tableView headerBeginRefreshing];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestData) name:@"KrequestData" object:nil];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)setRightItem{
    if (self.vcType == AlreadySignType || self.vcType == SenderSinType) {
        UIBarButtonItem * rightIem = [[UIBarButtonItem alloc] initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(searchAction)];
        self.navigationItem.rightBarButtonItem = rightIem;
    }

}


-(void)requestData{
    
    if (self.isSearching) {
        self.currentPage = 1;
        self.searchText = self.searchText.length !=0 ? self.searchText : @"";
        [self loadSearchData:self.searchText];
        
    }else{
        NSString * method = nil;
        NSString * URL = nil;
             if (self.vcType == WaitForSignType) { //待收文件
            method = KexhcangePageMethod;
            URL = KexchexchangeURL;
            self.title = @"待收文件";
        }else if (self.vcType == AlreadySignType){ //已收文件
            method = KreceivedExhcangePageMethod;
            URL = KexchexchangeURL;
            self.title = @"已收文件";
        }else if (self.vcType == SenderSinType){ //已发文件
            method = KsendExhcangePageMethod;
            URL = KexchexchangeURL;
            self.title = @"已发文件";
        }else if(self.vcType == WaitForReadType){//待阅
            method = KReadFilePage;
            URL = KexchgeneralURL;
            self.title = @"待阅文件";
        }        self.currentPage = 1;
        NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
        NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
        __weak typeof(self) weakSelf = self;
        [HttpTools requestWithURL:URL arrays:array method:method success:^(id JSON) {
            weakSelf.contentsArray = [DueInListModel dataWithArray:JSON[@"data"]];
            weakSelf.totalNumber = [JSON[@"number"] integerValue];
            [weakSelf.tableView headerEndRefreshing];
            [weakSelf.tableView reloadData];
            weakSelf.currentPage++;
        } failure:^(NSError *error) {
            [weakSelf.tableView headerEndRefreshing];
        }];
    }
}

-(void)requestMoreData{
    
    if (self.isSearching) {
        self.searchText = self.searchText.length !=0 ? self.searchText : @"";
        [self loadSearchData:self.searchText];
        
    }else{
        NSString * method = nil;
        NSString * URL = nil;
             if (self.vcType == WaitForSignType) { //待收文件
            method = KexhcangePageMethod;
            URL = KexchexchangeURL;
            self.title = @"待收文件";
        }else if (self.vcType == AlreadySignType){ //已收文件
            method = KreceivedExhcangePageMethod;
            URL = KexchexchangeURL;
            self.title = @"已收文件";
        }else if (self.vcType == SenderSinType){ //已发文件
            method = KsendExhcangePageMethod;
            URL = KexchexchangeURL;
            self.title = @"已发文件";
        }else if(self.vcType == WaitForReadType){//待阅
            method = KReadFilePage;
            URL = KexchgeneralURL;
            self.title = @"待阅文件";
        }        NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
        NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
        __weak typeof(self) weakSelf = self;
        [HttpTools requestWithURL:URL arrays:array method:method success:^(id JSON) {
            
            NSArray * tempArray = [DueInListModel dataWithArray:JSON[@"data"]];
            [weakSelf.contentsArray  addObjectsFromArray:tempArray] ;
            weakSelf.totalNumber = [JSON[@"number"] integerValue];
            [weakSelf.tableView footerEndRefreshing];
            [weakSelf.tableView reloadData];
            weakSelf.currentPage++;
        } failure:^(NSError *error) {
            [weakSelf.tableView footerEndRefreshing];
        }];

    }
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.contentsArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static  NSString * cellId = @"Cellid";
    FileListCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"FileListCell" owner:self options:nil] lastObject];
    }
    DueInListModel * model = self.contentsArray[indexPath.row];
    cell.titleLabel.text = model.subject;
    if (model.exchangeCategory && model.exchangeUnit) {
         cell.subjectLabel.text = [NSString stringWithFormat:@"%@/%@/%@",model.exchangeTime,model.exchangeCategory,model.exchangeUnit];
    }else{
         cell.subjectLabel.text = [NSString stringWithFormat:@"%@",model.exchangeTime];
    }
   
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    DueInListModel * model = self.contentsArray[indexPath.row];
    CGFloat height = 0;
    height = [OAToolBox sizebyText:model.subject font:14 minsWidth:55];
    
    return 8 + height + 5 + 21 +8;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DueInListModel * model = self.contentsArray[indexPath.row];
    if (self.vcType == WaitForSignType) {
        
        [UIAlertView showWithTitle:nil message:@"确认是否签收" cancelButtonTitle:@"否" otherButtonTitles:@[@"是"] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                MBProgressHUD * hud =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                hud.labelText = @"签收中";
                NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
                NSArray * array = @[@{@"userId":userId},@{@"unid":model.identification}];
                __weak typeof(self) weakSelf = self;
                [HttpTools requestWithURL:KexchexchangeURL arrays:array method:KsignExhcangeMethod success:^(id JSON) {
                    [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
                    [weakSelf.view.window makeToast:@"签收成功"];
                    OADueInDetailController * detaiVC = (OADueInDetailController*)[self.storyboard instantiateViewControllerWithIdentifier:@"DueInDetailVC"];
                    detaiVC.exchangeForm = model.exchangeForm;
                    detaiVC.identifier = model.identification;
                    detaiVC.vcType = self.vcType;
                     [self refreshData]; //刷新数据
                    [self.navigationController pushViewController:detaiVC animated:YES];
                   
                } failure:^(NSError *error) {
                    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                    [weakSelf.view.window makeToast:@"签收失败"];
                }];
            }
            
        }];
    }else if (self.vcType == AlreadySignType || self.vcType == SenderSinType || self.vcType == WaitForReadType){
        OADueInDetailController * detaiVC = (OADueInDetailController*)[self.storyboard instantiateViewControllerWithIdentifier:@"DueInDetailVC"];
        detaiVC.exchangeForm = model.exchangeForm;
        detaiVC.identifier = model.identification;
        detaiVC.vcType = self.vcType;
        [self.navigationController pushViewController:detaiVC animated:YES];
    }

}

#pragma mark 搜素
-(void)searchAction{

    [UIAlertView showWithTitle:@"搜索" message:nil style:UIAlertViewStylePlainTextInput cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
        [self.view endEditing:YES];
        
        if (buttonIndex == 1) {
            UITextField * textField = [alertView textFieldAtIndex:0];
            if (textField.text.length !=0) {
                
                [self.contentsArray removeAllObjects];
                self.isSearching = YES;
                self.currentPage = 1;
                [self loadSearchData:textField.text];
            }
         
        }
        
    }];
    
}

-(void)loadSearchData:(NSString*)text{
     NSString * method = nil;
    self.searchText = text;
  if (self.vcType == WaitForSignType) { //待收文件
        method = KCollectSearchMethod;
    }else if (self.vcType == AlreadySignType){ //已收文件
        method = KReceivedSearchMethod;
    }else if (self.vcType == SenderSinType){ //已发文件
        method = KPostedSearchMethod;
    }
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"Condition":text},@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    __weak typeof(self) weakSelf = self;
    [HttpTools requestWithURL:KexchangeSubstanceURL arrays:array method:method success:^(id JSON) {
        if (self.currentPage == 1) {
            [self.contentsArray removeAllObjects];
        }
        NSArray * tempArray = [DueInListModel dataWithArray:JSON[@"data"]];
        [weakSelf.contentsArray  addObjectsFromArray:tempArray];
        weakSelf.totalNumber = [JSON[@"number"] integerValue];
        [weakSelf.tableView footerEndRefreshing];
        [weakSelf.tableView reloadData];
        weakSelf.currentPage++;
        
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
        
    } failure:^(NSError *error) {
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
    }];

    
}


@end
